package com.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * AOP实现日志记录
 */
@Aspect
@Component
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //指定拦截controller包下的所有方法：返回值类型 包名.类名.方法名(参数)
    @Pointcut("execution(* com.blog.controller.*.*(..))")
    public void log(){
        logger.info("数据已拦截--------------");
    }

    //前置通知
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        //通过servlet获取url和ip
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();

        //通过JoinPoint获取方法和参数
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
        logger.info("Request : {}",requestLog);
    }


    //后置通知
    @AfterReturning(returning = "result",pointcut="log()")
    public  void doAfterReturn(Object result){
        logger.info("Result : {}",result);
    }

    //最终通知
    @After("log()")
    public void doAfter(){
        logger.info("--------doAfter--------");
    }

    //返回内容-封装成一个内部类
    private class RequestLog{
        private String url;         //请求url
        private String ip;          //访问者ip
        private String classMethod; //调用方法classMethod
        private Object[] args;      //参数args

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
